#include "AppDelegate.h"
#include "UISceneSwitcher.h"
#include <cmath>

UISceneSwitcher * UISceneSwitcher::create(UISS_MODE mode, UISS_ACTION action)
{
	UISceneSwitcher* uiss = new UISceneSwitcher();
	if (!uiss->init()) return nullptr;
	uiss->mode = mode;
	uiss->action = action;

	auto diagonal = sqrtf(frameSize.width*frameSize.width + frameSize.height*frameSize.height);
	auto parta = LayerColor::create(Color4B::WHITE, diagonal, diagonal / 2);
	auto partb = LayerColor::create(Color4B::WHITE, diagonal, diagonal / 2);

	UI::setNodeAnch(parta, ANCH_MB);
	UI::setNodeAnch(partb, ANCH_MT);

	auto linea = LayerGradient::create(Color4B::WHITE, UICOMFGB);
	linea->changeWidthAndHeight(diagonal, 50);
	parta->addChild(linea);
	uiss->addChild(parta);

	auto lineb = LayerGradient::create(UICOMFGB, Color4B::WHITE);
	lineb->changeWidthAndHeight(diagonal, 50);
	lineb->setPosition(0, diagonal / 2 - 50);
	partb->addChild(lineb);
	uiss->addChild(partb);

	auto angle = 180 / M_PI * atanf(frameSize.height / frameSize.width);
	switch (mode)
	{
		case TOPBUTTOM:
			uiss->ax = frameSize.width / 2; uiss->ay = frameSize.height;
			uiss->bx = frameSize.width / 2; uiss->by = 0;
			break;
		case LEFTRIGHT:
			uiss->ax = 0; uiss->ay = frameSize.height / 2;
			uiss->bx = frameSize.width; uiss->by = frameSize.height / 2;
			parta->setRotation(-90);
			partb->setRotation(-90);
			break;
		case LTRB:
			uiss->ax = 0; uiss->ay = frameSize.height;
			uiss->bx = frameSize.width; uiss->by = 0;
			parta->setRotation(-angle);
			partb->setRotation(-angle);
			break;
		case LBRT:
			uiss->ax = frameSize.width; uiss->ay = frameSize.height;
			uiss->bx = 0; uiss->by = 0;
			parta->setRotation(angle);
			partb->setRotation(angle);
			break;
		default:
			break;
	}
	if (action == ENTER)
	{
		parta->setPosition(frameSize.width / 2, frameSize.height / 2);
		partb->setPosition(frameSize.width / 2, frameSize.height / 2);
	}
	else
	{
		parta->setPosition(uiss->ax, uiss->ay);
		partb->setPosition(uiss->bx, uiss->by);
	}

	uiss->parta = parta;
	uiss->partb = partb;
	uiss->setLocalZOrder(65535);
	return uiss;
}

void UISceneSwitcher::play()
{
	float dura = .4f;
	if (action == ENTER)
	{
		parta->runAction(EaseSineInOut::create(MoveTo::create(dura, Vec2(ax, ay))));
		partb->runAction(EaseSineInOut::create(MoveTo::create(dura, Vec2(bx, by))));
	}
	else
	{
		parta->runAction(EaseSineInOut::create(MoveTo::create(dura, Vec2(frameSize.width / 2, frameSize.height / 2))));
		partb->runAction(EaseSineInOut::create(MoveTo::create(dura, Vec2(frameSize.width / 2, frameSize.height / 2))));
	}
	//runAction(Sequence::create(DelayTime::create(dura), RemoveSelf::create(), NULL));
}
